// components/filterIpt/filterIpt.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 搜索字段对象
    field: {
      type: Object,
      value: {},
      observer(newVal, oldVal) {

        let { start, end, field_id, dfltdate, dfltVal, type, } = newVal
        if((start || end)) {
          this.setData({
            initDate0: start,
            startDate: start,
            initDate1: end,
            endDate: end,
          })
          /*this.triggerChange({
            startDate: start,
            endDate: end,
          })*/
        }
        if(![undefined,null].includes(dfltdate)) {
          //240112 yan 日期默认值
          let {dateList} = newVal,
            dateOpt = dateList || this.data.dateList,
            dateIdx = dateOpt && dateOpt.findIndex(item => item[this.data.oid] === dfltdate);
          this.setData({
            dateIdx: dateIdx,
          })
          //240112 end
          this.setData({
            initDate2: dfltdate,
            oneDate: dfltdate,
          })
          // this.triggerChange(dfltdate)
        }
        // 起止搜索条件
        if(Array.isArray(field_id) && field_id.length === 2) {
          this.setData({
            fieldIdStart: field_id[0],
            fieldIdEnd: field_id[1]
          })
        } else {
          this.setData({
            fieldIdStart: '',
            fieldIdEnd: '',
          })
        }
        if(![null, undefined, ''].includes(dfltVal) && type === 'reference1') {  // 选择 默认值填充
          let { optionList, optionId, optionName, } = newVal
          if(Array.isArray(dfltVal) && dfltVal.length > 1) { // 起止默认值，数组形式
            let start = [undefined, null, '', ].includes(dfltVal[0]) ? '' : dfltVal[0],
                end = [undefined, null, '', ].includes(dfltVal[1]) ? '' : dfltVal[1]
            let filterStart = optionList.filter(opt => opt[optionId] == start),
                filterEnd = optionList.filter(opt => opt[optionId] == end),
                obj = {}
            if(filterStart.length) obj.selectedStartItem = filterStart[0]
            if(filterEnd.length) obj.selectedEndItem = filterEnd[0]
            if(filterStart.length || filterEnd.length) {
              this.triggerChange([ filterStart.length ? start : '', filterEnd.length ? end : ''])
            }
            this.setData(obj)
          } else if(typeof dfltVal !== 'object') {  // 单个默认值
            let filterArr = optionList.filter(opt => opt[optionId] == dfltVal)
            if(filterArr.length) {
              this.setData({
                selectedItem: filterArr[0],
              })
              this.triggerChange(dfltVal)
            }
          }
        }

        //240112 yan 增加picklist默认值
        if (![null, undefined, ''].includes(dfltVal) && type === 'picklist') {
          let { optionList, optionId, optionName, } = newVal
          let ind = optionList.findIndex(opt => opt[optionId] == dfltVal)
          this.setData({
            radioIdx: ind,
          })
          this.triggerChange(optionList[ind] ? optionList[ind][optionId] : '')
        }
        //240112 end

        this.initData()
      },
    },
    // 重置输入值标识
    reset: {
      type: Boolean,
      value: false,
      observer(newVal, oldVal) {
        let { type, optionList, } = this.data.field,
            { resetFlag0, resetFlag1, resetFlag2, } = this.data,
            resetObj = {
              radioIdx: null,
              selectedItem: {},
              selectedStartItem: {},
              selectedEndItem: {},
              dateIdx: null,
              startDate: '',
              resetFlag0: !resetFlag0,
              endDate: '',
              resetFlag1: !resetFlag1,
              val: '',
              valStart: '',
              valEnd: '',

              oneDate: '',
              resetFlag2: !resetFlag2,
            }

        // if(type === 'checkbox') resetObj.optList = JSON.parse(JSON.stringify(optionList))
        if(['picklist', 'multiple', ].includes(type)) {
          resetObj.optList = JSON.parse(JSON.stringify(optionList))
        }
        this.setData(resetObj)
      },
    },

  //  传入条件值
    data: {
      type: Object,
      observer(newVal){
        let { start, end, field_id, dfltdate, dfltVal, type, } = this.data.field;
        if (newVal[field_id] !== undefined){

          if (type === 'picklist'){
            let { optionList, optionId, optionName, } = this.data.field
            let ind = optionList.findIndex(opt => opt[optionId] == newVal[field_id])
            this.setData({
              radioIdx: ind,
            })
          }

          if (type === 'datetime') {
            let {start,end,date} = newVal[field_id];
            if((start || end)) {
              this.setData({
                initDate0: start,
                startDate: start,
                initDate1: end,
                endDate: end,
              })
            }
            if(![undefined,null].includes(date)) {
              //240112 yan 日期默认值
              let {dateList} = newVal,
                dateOpt = dateList || this.data.dateList,
                dateIdx = dateOpt && dateOpt.findIndex(item => item[this.data.oid] === dfltdate);
              this.setData({
                dateIdx: dateIdx,
              })
              //240112 end
              this.setData({
                initDate2: dfltdate,
                oneDate: dfltdate,
              })
            }
          }
        }

      }
    }
  },

  // 监听
  observers: {
    // field(val) {
    //   let { start, end,  } = val
    //   if(!isInit && (start || end)) {
    //     this.setData({
    //       initDate0: start,
    //       startDate: start,
    //       initDate1: end,
    //       endDate: end,
    //     })
    //     this.triggerChange({
    //       startDate: start,
    //       endDate: end,
    //     })
    //   }
    //   // if()
    //   console.log(val);
    //   this.initData()
    // },
    // reset(val) {
    //   if(isInit) {
    //     let { type, optionList, } = this.data.field,
    //         { resetFlag0, resetFlag1, } = this.data,
    //         resetObj = {
    //           radioIdx: null,
    //           selectedItem: {},
    //           dateIdx: null,
    //           startDate: '',
    //           resetFlag0: !resetFlag0,
    //           endDate: '',
    //           resetFlag1: !resetFlag1,
    //           val: '',
    //         }

    //     // if(type === 'checkbox') resetObj.optList = JSON.parse(JSON.stringify(optionList))
    //     if(['picklist', 'multiple', ].includes(type)) {
    //       resetObj.optList = JSON.parse(JSON.stringify(optionList))
    //     }
    //     this.setData(resetObj)
    //   }
    // },

  },

  /**
   * 组件的初始数据
   */
  data: {
    // 字段起止
    fieldIdStart: '',
    fieldIdEnd: '',

    optList: [],              // radio/checkbox/select选项
    oid: 'id',                // 选项id别名
    name: 'name',             // 选项name别名

    radioIdx: null,

    selectFlag: false,        // 选项列表弹层弹出标识
    selectedValKey: '',
    selectedItem: {},         // 选中的选项
    selectedStartItem: {},    // 开始选中的选项
    selectedEndItem: {},      // 结束选中的选项


    dateIdx: null,
    dateList: [               // 日期选择
      // { id: '昨日', name: '昨日', },
      // { id: '上周', name: '上周', },
      // { id: '上月', name: '上月', },
      // { id: '本日', name: '本日', },
      // { id: '本周', name: '本周', },
      // { id: '本月', name: '本月', },
      { id: 0, name: '今天', },
      { id: 1, name: '近7天', },
      { id: 2, name: '本月', },
      { id: 3, name: '本季', },
      { id: 4, name: '本年', },
    ],
    dateFlag0: false,         // 日历弹层弹出标识
    initDate0: '',            // 日历初始日期
    resetFlag0: false,        // 日历重置标识
    startDate: '',            // 选中的开始日期
    dateFlag1: false,         // 日历弹层弹出标识
    initDate1: '',
    resetFlag1: false,
    endDate: '',              // 选中的结束日期

    // 单个日期，非日期范围
    dateFlag2: false,         // 日历弹层弹出标识
    initDate2: '',
    resetFlag2: false,
    oneDate: '',

    // text/num/digit
    val: '',
    valStart: '',
    valEnd: '',
    valFlag: false,
    valStartFlag: false,
    valEndFlag: false,

    // bit
    bool: null
  },

  // 生命周期
  lifetimes: {
    created() {},
    attached() {},
    ready() {},
    moved() {},
    detached() {},
    error() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    initData() {
      let { type, optionList, optionId, optionName, dateList} = this.data.field,
        obj = '';
      if(optionList && optionList.length) {
        if(['picklist', 'multiple', ].includes(type)) {
          if(!optionId) optionId = 'label'
          if(!optionName) optionName = 'label'
        }
        let oid = optionId === undefined ? 'row_id' : optionId,
            name = optionName === undefined ? 'name' : optionName;

          obj = {
            optList: JSON.parse(JSON.stringify(optionList)),
            oid: oid,
            name: name,
          };
      }
      //221126 yan 修改 自定义传入日期选择
      if (dateList)obj = {...obj,dateList};
      obj && this.setData(obj)
    },

    // radio/checkbox
    checkRadio(e) {
      let radioIdx = this.data.radioIdx,
          { idx, item, } = e.currentTarget.dataset
      this.setData({
        radioIdx: radioIdx === idx ? null : idx,
      })
      let id = this.data.oid
      this.triggerChange(radioIdx === idx ? '' : item[id],)
    },
    checkCheckbox(e) {
      let { optList, oid, } = this.data,
          idx = e.currentTarget.dataset.idx,
          vals = []
      optList[idx].checked = !optList[idx].checked
      this.setData({
        optList: [ ...optList ],
      })

      optList.forEach((item) => {
        if(item.checked) vals.push(item[oid])
      })
      this.triggerChange(vals.length ? vals : '')
    },

    // select
    toggleFlag(e) {
      let { key, valkey, } = e.currentTarget.dataset
      if(valkey) this.data.selectedValKey = valkey
      this.setData({
        [key]: !this.data[key],
      })
    },
    select(e) {
      let { selectedValKey, oid, } = this.data,
          key = selectedValKey || 'selectedItem'
      this.setData({
        [key]: e.detail,
      })
      if(selectedValKey) {  // 起止
        let { selectedStartItem, selectedEndItem, } = this.data
        this.triggerChange([selectedStartItem[oid], selectedEndItem[oid]])
      } else {
        this.triggerChange(e.detail[oid],e.detail)
      }
    },

    // date
    checkDate(e) {
      let dateIdx = this.data.dateIdx,
          { idx, item, } = e.currentTarget.dataset
      this.setData({
        dateIdx: dateIdx === idx ? null : idx,
      })
      if(dateIdx !== idx) {
        let { resetFlag0, resetFlag1, } = this.data
        this.setData({
          resetFlag0: !resetFlag0,
          startDate: '',
          resetFlag1: !resetFlag1,
          endDate: '',
        })
      }

      this.triggerChange(dateIdx === idx ? '' : item[this.data.oid])
    },
    selectDate(e) {
      let key = e.currentTarget.dataset.key,
          obj = {
            [key]: e.detail,
          }
      if(obj[key]) obj.dateIdx = null
      this.setData(obj)
      let { startDate, endDate, } = this.data,
          val = {
            startDate,
            endDate,
          }
      this.triggerChange(val)
    },
    selectOneDate(e) {
      let key = e.currentTarget.dataset.key,
          obj = {
            [key]: e.detail,
          }
      this.setData(obj)
      this.triggerChange(e.detail)
    },

    // input&other
    // 双向绑定 报警告处理
    inputIpt(e) {},
    inputNumIpt(e) {
      let { value, } = e.detail,
          { key, valflag, } = e.currentTarget.dataset,
          // reg = /^(\-)?(\d+)?(\.(\d+)?)?$|^(\.)?(\d+)$/
          reg = /^(\-)?(\d+(\.)?(\d+)?)?$|^(\.)?(\d+)?$/
      // let reg =  /^(\-|\+)?\d+(\.\d+)?$/
      if(value) {
        if(reg.test(value)) {
          this.data[key] = value
        } else {
          // this.setData({
          //   [key]: this.data[key],
          // })
          let prevVal = this.data[key]
          return {
            value: prevVal,
          }
        }
      } else if(value !== this.data[key]) {
        this.data[key] = value
      }

      if(this.data[key]) {
        if(!this.data[valflag]) {
          this.setData({
            [valflag]: true,
          })
        }
      } else {
        if(this.data[valflag]) {
          this.setData({
            [valflag]: false,
          })
        }
      }
    },
    inputBlur(e) {
      // let val = e.detail.value

      let { fieldIdStart, valStart, valEnd, val, field, } = this.data
      if(['num', 'digit',].includes(field.type)) {
        if(valStart) valStart = this.toNum(valStart)
        if(valEnd) valEnd = this.toNum(valEnd)
        if(val) val = this.toNum(val)
      }
      if(fieldIdStart) {
        this.triggerChange([valStart, valEnd])
      } else {
        this.triggerChange(val)
      }
    },
    toNum(val) {
      return isNaN(val) ? '' : Number(val)
    },

    emptyIpt(e) {
      let { key, } = e.currentTarget.dataset,
          { fieldIdStart, fieldIdEnd, field, oid, } = this.data,
          flagKey = key + 'Flag',
          obj = {
            [key]: '',
          }
      if(typeof this.data[key] === 'object') obj[key] = {}
      if(this.data[flagKey] !== undefined) obj[flagKey] = false
      this.setData(obj)

      let { type, } = field
      if(fieldIdStart || fieldIdEnd) {  // 起止字段
        let { selectedStartItem, selectedEndItem, valStart, valEnd, } = this.data
        if(type === 'reference1') { // 选择
          this.triggerChange([selectedStartItem[oid], selectedEndItem[oid]])
        } else {
          this.triggerChange([valStart, valEnd])
        }
      } else if(['datetime', 'date', ].includes(type)) { // 日期范围
        let { startDate, endDate, } = this.data
        this.triggerChange({
          startDate,
          endDate,
        })
      } else if(type === 'reference1') {
        this.triggerChange(obj[key][oid] === undefined ? '' : obj[key][oid])
      } else {
        this.triggerChange(obj[key])
      }
    },

    //bit
    bindSwitchChange(e){
      let bool = e.detail;
      this.setData({bool});
      this.triggerChange(bool)
    },

    triggerChange(val,optItem) {
      let { field_id, type, } = this.data.field,
          obj = {
            field_id,
            type,
            val,
            optItem
          }
      if(!['picklist', 'multiple', 'reference1', 'reference', 'datetime', 'date', 'bit'].includes(type)) type = 'text';
      console.log(obj);
      this.triggerEvent('change', obj)
    },
  },
})
